package cn.net.susan.consumer;

import cn.hutool.json.JSONUtil;
import cn.net.susan.entity.common.CommonNotifyEntity;
import cn.net.susan.mapper.common.CommonNotifyMapper;
import cn.net.susan.util.FillUserUtil;
import cn.net.susan.websocket.WebSocketServer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

import static cn.net.susan.config.RabbitConfig.EXCEL_EXPORT_QUEUE;

/**
 * excel导出消息接收者
 *
 * @author 苏三，该项目是知识星球：java突击队 的内部项目
 * @date 2024/3/10 下午5:09
 */
@Slf4j
@Component
public class ExcelExportConsumer {

    @Autowired
    private CommonNotifyMapper commonNotifyMapper;


    @RabbitListener(queues = EXCEL_EXPORT_QUEUE)
    public void handler(Message message) throws IOException {
        byte[] body = message.getBody();
        String content = new String(body);
        log.info("ExcelExportConsumer接收到消息：{}", content);
        CommonNotifyEntity commonTaskEntity = JSONUtil.toBean(content, CommonNotifyEntity.class);
        pushNotify(commonTaskEntity);
    }


    private void pushNotify(CommonNotifyEntity commonNotifyEntity) {
        try {
            WebSocketServer.sendMessage(commonNotifyEntity);

            commonNotifyEntity.setIsPush(1);
            FillUserUtil.mockCurrentUser();
            commonNotifyMapper.update(commonNotifyEntity);
        } catch (IOException e) {
            log.error("WebSocket通知推送失败，原因：", e);
        } finally {
            FillUserUtil.clearCurrentUser();
        }
    }
}
